<?php
namespace Easy\Response;

class JsonResponse extends AbstractResponse
{
    public static function succOut($data)
    {
        $respDTO = ResponseDTO::fromArr(
            ['data' => $data, 'code' => ResponseCode::CODE_200, 'msg' => '']
        );
        self::out($respDTO);
    }

    public static function failOut($msg)
    {
        $respDTO = ResponseDTO::fromArr([
            'data' => [], 'code' => ResponseCode::CODE_500, 'msg' => $msg,
        ]);
        self::out($respDTO);
    }

    public static function out(ResponseDTO $responseDTO)
    {
        $runName = php_sapi_name();
        if ($responseDTO->code && $runName == self::PHP_RUN_IN_FPM) {
            ResponseCode::headerCode($responseDTO->code);
            $responseDTO = self::getDefaultData($responseDTO);
            exit($responseDTO->toJson());
        } else {
            throw new \RuntimeException($responseDTO->msg, $responseDTO->code);
        }
    }
}